package com.zx.flow.core.execute.eventhandler;

import com.zx.flow.api.dict.FlowDict.Event;
import com.zx.flow.api.dict.FlowDict.OperatorRule;
import com.zx.flow.api.execute.model.FlowContext;
import com.zx.flow.api.execute.model.FlowNode;
import com.zx.flow.api.execute.request.FlowParamCommunicateAnswer;
import com.zx.flow.api.execute.request.FlowParamNodeEntry;
import com.zx.flow.api.execute.request.FlowParamNodeFinish;
import com.zx.flow.api.execute.response.FlowResult;
import com.zx.flow.api.util.AssertUtil;
import com.zx.flow.core.execute.EventHandler;

/**
 * 事件处理器【流程->沟通回复】
 */
public class EventFlowCommunicateAnswerHandler extends EventHandler<FlowParamCommunicateAnswer> {

    @Override
    public boolean in(FlowContext flow, FlowParamCommunicateAnswer param) {
        AssertUtil.checkOperator(flow, param.getNodeId(), param.getAccountCode(), OperatorRule.communicate);
        return flow != null;
    }

    @Override
    public FlowResult on(FlowContext flow, FlowParamCommunicateAnswer param) {
        // 获得当前节点
        FlowNode currentNode = AssertUtil.checkCurrentNodeId(flow, param.getNodeId());
        // 结束当前节点
        flow = this.execute(new FlowParamNodeFinish(param.getId(), param.getNodeId(), currentNode.getNodeCurrentCode(),
                Event.nodeCommunicateAnswer, param.getRemark(), param.getAccountCode())).getFlowContext();
        // 获得需要回复的节点
        FlowNode oldNode = this.getNode(param.getId(), currentNode.getNodeFormId());
        // 开始新节点
        FlowParamNodeEntry paramNodeEntry = new FlowParamNodeEntry(flow.getId(), currentNode.getNodeCurrentCode(),
                oldNode.getOperators());
        paramNodeEntry.setNodeFormId(oldNode.getNodeFormId());
        flow = this.execute(paramNodeEntry).getFlowContext();
        // 触发监听
        this.listener(currentNode, Event.nodeCommunicateAnswer);
        return FlowResult.ok(flow);
    }

}
